package com.king.base.rest.dept;
import com.king.base.aop.DataScope;
import com.king.base.aop.Log;
import com.king.base.domain.dept.Dept;
import com.king.base.msg.BaseResponseEntity;
import com.king.base.service.dept.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Spur
 * @date 2019/6/24
 */
@RestController
@RequestMapping(value = "api/core/dept")
@Api(value = "dept",description = "部门管理Controller")
public class DeptController {
    @Autowired
    private DeptService deptService;
    @GetMapping(value = "/getById/{id}")
    @ApiOperation(value = "根据ID获取一个部门实例")
    public BaseResponseEntity getById(@PathVariable String id){
        return new BaseResponseEntity(deptService.getById(id));
    }
    @GetMapping(value = "/list")
    @ApiOperation(value = "部门树形列表")
    @Log(description = "部门查询")
    @DataScope(deptAlias = "t")
    public BaseResponseEntity list(Dept dept){
        List<Dept> deptList=deptService.selectDeptList(dept);
        return new BaseResponseEntity(deptService.buildDeptTree(deptList));
    }
    @GetMapping(value = "/tree")
    @ApiOperation(value = "部门下拉选择器")
    public BaseResponseEntity tree(Dept dept){
        List<Dept> deptList=deptService.selectDeptList(dept);
        return new BaseResponseEntity(deptService.buildDeptTreeSelect(deptList));
    }
    @PostMapping(value = "/create")
    @ApiOperation(value = "部门创建")
    @Log(description = "部门创建")
    public BaseResponseEntity create(@RequestBody Dept dept){
        if(deptService.checkDeptNameUnique(dept)){
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"部门"+dept.getDeptName()+"已经存在");
        }
        return new BaseResponseEntity(deptService.saveOrUpdate(dept));
    }
    @PutMapping(value = "/update")
    @ApiOperation(value = "部门修改")
    @Log(description = "部门修改")
    public BaseResponseEntity update(@RequestBody Dept dept){
        if(deptService.checkDeptNameUnique(dept)){
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"部门"+dept.getDeptName()+"已经存在");
        }
        return new BaseResponseEntity(deptService.saveOrUpdate(dept));
    }
    @DeleteMapping(value = "/delete/{deptId}")
    @ApiOperation(value = "部门删除")
    @Log(description = "部门删除")
    public BaseResponseEntity delete(@PathVariable String deptId){
        if(deptService.hasChildByDeptId(deptId)){
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"请先删除子部门");
        }
        if(deptService.checkDeptExistUser(deptId)){
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"部门存在用户,不允许删除");
        }
        deptService.removeById(deptId);
        return new BaseResponseEntity("删除成功!");
    }
}
